﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;
using System.Web.SessionState;
using QLHD.Models;
using QLHD.Utilities;

namespace JQueryFileUpload
{
    public class FileUploadHandler : IHttpHandler, IRequiresSessionState
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (context.Session["MaHD"] == null)
                    return;
                int mahd = int.Parse(context.Session["MaHD"].ToString());


                //Uploaded File Deletion
                string uploadpath = ConfigurationManager.AppSettings["UploadPath"];
                if (string.IsNullOrEmpty(uploadpath))
                    uploadpath = "/Uploads";

                List<PermissionsUser> gps = new AuthenticationHelper().GetUserPermissions();


                if (context.Request.QueryString.Count > 0)
                {

                    string filename = "";
                    if (!string.IsNullOrEmpty(context.Request.QueryString["del"]))
                    {
                        filename = Path.GetFileName(context.Request.QueryString["del"].ToString()).Trim();
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString["dl"]))//download
                    {
                        filename = Path.GetFileName(context.Request.QueryString["dl"].ToString()).Trim();
                    }
                    QLHD2013Entities db = new QLHD2013Entities();
                    TaiLieu tl = db.TaiLieux.Where(q => q.MaHD == mahd && q.FilePath.ToLower().EndsWith(filename.ToLower())).FirstOrDefault();
                    int usp = 0;
                    int? pid = null;
                    if (tl == null)
                    {
                        context.Response.Write("error");
                        return;
                    }
                    if (tl.HopDong.HopDong3 != null)
                        pid = tl.HopDong.HopDong3.DepartmentID;
                    else
                    {
                        pid = tl.HopDong.DepartmentID;
                    }

                    if (gps.Where(q => q.ObjectID == 1 && q.ItemID == pid).Count() > 0)
                        usp = gps.Where(q => q.ObjectID == 1 && q.ItemID == pid).Max(q => q.PermissionValue);

                    if (usp < 3)
                    {
                        context.Response.Write("accessdenied");
                        return;
                    }
                    if (tl != null && !string.IsNullOrEmpty(context.Request.QueryString["del"]))
                    {
                        string savepath = context.Server.MapPath("~").TrimEnd('/') + tl.FilePath;
                        db.DeleteObject(tl);
                        db.SaveChanges();
                        File.Delete(savepath);
                        context.Response.Write("success");
                    }
                    else if (tl != null && !string.IsNullOrEmpty(context.Request.QueryString["dl"]))
                    {
                        string fullpath = context.Server.MapPath("~").TrimEnd('/') + tl.FilePath;
                        if (File.Exists(fullpath))
                        {
                            context.Response.ContentType = "application/octet-stream";
                            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(tl.FilePath)));
                            context.Response.WriteFile(fullpath);
                        }
                        else
                        {
                            context.Response.ContentType = "text/plain";
                            context.Response.Write("Tài liệu này không tồn tại!");
                        }
                    }
                }
                //File Upload
                else
                {
                    string datefolder = DateTime.Now.ToString("yyyy-MM-dd");
                    uploadpath += "/" + datefolder;
                    string abspath = context.Server.MapPath("~").TrimEnd('/') + uploadpath.TrimEnd('/');
                    if (!Directory.Exists(abspath))
                    {
                        Directory.CreateDirectory(abspath);
                    }
                    string fileName = Path.GetFileName(context.Request.Files[0].FileName);
                    string location = abspath + "/" + fileName;
                    QLHD2013Entities db = new QLHD2013Entities();
                    TaiLieu tl = db.TaiLieux.Where(q => q.MaHD == mahd && q.FilePath.ToLower().EndsWith(fileName.ToLower())).FirstOrDefault();
                    if (tl == null)
                    {
                        HopDong hd = db.HopDongs.Where(q => q.MaHD == mahd).FirstOrDefault();
                        if (hd == null)
                        {
                            context.Response.Write("error");
                            return;
                        }
                        int usp = 0;
                        int? pid = null;
                        if (hd.HopDong3 != null)
                            pid = hd.HopDong3.DepartmentID;
                        else
                        {
                            pid = hd.DepartmentID;
                        }

                        if (gps.Where(q => q.ObjectID == 1 && q.ItemID == pid).Count() > 0)
                            usp = gps.Where(q => q.ObjectID == 1 && q.ItemID == pid).Max(q => q.PermissionValue);

                        if (usp < 3)
                        {
                            context.Response.Write("accessdenied");
                            return;
                        }

                        context.Request.Files[0].SaveAs(location);
                        tl = TaiLieu.CreateTaiLieu(0, mahd, DateTime.Now);
                        tl.FilePath = uploadpath + "/" + fileName;
                        db.AddToTaiLieux(tl);
                        db.SaveChanges();
                        context.Response.Write("success");
                    }
                    else
                    {
                        context.Response.Write("exist");
                    }
                }
            }
            catch
            {

            }
        }

        #endregion
    }
}
